<?php
/**
 * Created by PhpStorm.
 * User: yuanjie
 * Date: 2017/5/15
 * Time: 下午4:44
 */
class ScsAccountController extends BaseController {
    /**
     * @Author:      lyt
     * @DateTime:  2017-05-24 16:16:54
     * @Description: 添加科目分类的接口
     */
    public function account_subject(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $sa = SubjectAccount::get();

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("sa_info"=>$sa));
        } while (false);
        // Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "account_subject", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    public function arrears_detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
                'shop_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get("user_id");
            $shop_id = Input::get("shop_id");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            //欠款总数
            $arrears_all_detail = UserAccountDeatails::where('user_id',$user_id)->where('acount_type',3)->sum('balance');
            $arrears_shop_detail=0;
            //门店欠款总数
            //$arrears_shop_detail = UserAccountDeatails::where('user_id',$user_id)->where('shop_id',$shop_id)->where('acount_type',3)->sum('balance');
            // $orders = Orders::where('shop_id',$shop_id)
            //     ->where('user_id',$user_id)
            //     ->whereIn('status',array(1017,1117,1217,1317,1417,1018))
            //     ->where('verify_status',0)
            //     ->select('order_id')
            //     ->get()
            //     ->toArray();

            // $arrears_shop_detail = OrderPayRecord::where('pay_type',6)
            //     ->where('status',1)
            //     ->whereIn('order_id',$orders)
            //     ->sum('amount');


            $order_amount=DB::select("select o.pay_user_id,sum(opr.amount) as amount from order_pay_record opr join orders o on o.order_id=opr.order_id JOIN users on users.id=o.pay_user_id where opr.pay_type=6 and opr.`status`=1 and users.type=2 and o.place=2 and o.shop_id=? and o.verify_status=0  and o.`status` in (1018,1017,1217,1317,1417)  and o.pay_user_id =?",array($sc_user->shop_id,$user_id));
            $arrears_shop_detail=$arrears_shop_detail+$order_amount[0]->amount;
            
            //统计所有企业 洗车单欠款
            $wash_order_amount=DB::select("SELECT cwo.user_id,sum(cwopr.amount) as amount FROM  car_wash_order_pay_record cwopr LEFT JOIN car_wash_order cwo ON cwo.order_id = cwopr.order_id LEFT JOIN users u ON u.id = cwo.user_id WHERE  cwopr.pay_type = 6 AND cwopr.`status` = 1 AND u.type = 2 AND cwo.verify_status = 0 and cwo.`status`=1417 and cwo.shop_id=? and cwo.user_id =?",array($sc_user->shop_id,$user_id));
            $arrears_shop_detail=$arrears_shop_detail+$wash_order_amount[0]->amount;

            //所有的 套餐卡销售退款
            $sc_order_amount=DB::select("SELECT sco.user_id,sum(cwopr.amount) as amount FROM  service_card_order_pay_record cwopr LEFT JOIN service_card_order sco ON sco.order_id = cwopr.order_id LEFT JOIN users u ON u.id = sco.user_id WHERE  cwopr.pay_type = 6 AND cwopr.`status` = 1 AND u.type = 2 AND sco.verify_status = 0 and sco.`status`=1417 and sco.shop_id=? and sco.user_id=?",array($sc_user->shop_id,$user_id));
            $arrears_shop_detail=$arrears_shop_detail+$sc_order_amount[0]->amount;

            //所有企业的欠款退货统计 
            $return_amount=DB::select("select o.pay_user_id,sum(ror.amount) as amount from return_order_record  ror join return_order ro on ro.id=ror.return_order_id join orders o on o.order_id =ro.order_id  join users on users.id =o.pay_user_id where ror.pay_type=6 and ro.`status`=1 and users.type=2 and o.place=2 and o.shop_id=? and ro.verify_status=0 and o.pay_user_id=?",array($sc_user->shop_id,$user_id));
            $arrears_shop_detail=$arrears_shop_detail-$return_amount[0]->amount;
            //所有企业的洗车单欠款退货 
            $car_return_amount=DB::select("SELECT  cwo.user_id,sum(rwr.amount) as amount
                FROM `return_washorder_record` rwr
                LEFT JOIN return_carwash_order rco ON rco.id = rwr.return_washorder_id
                LEFT JOIN car_wash_order cwo ON cwo.order_id = rco.order_id
                LEFT JOIN users u ON u.id = cwo.user_id where rwr.pay_type=6 AND rco.`status` = 1 and u.type=2 and rco.verify_status=0 and cwo.shop_id=? and cwo.user_id=?",array($sc_user->shop_id,$user_id));
            $arrears_shop_detail=$arrears_shop_detail-$car_return_amount[0]->amount;

            //所有套餐卡销售退款
            $service_return_amount=DB::select("SELECT   sco.user_id,sum(rscr.amount) as amount
                FROM
                return_service_card_record rscr
                LEFT JOIN return_service_card_order rsco ON rsco.id = rscr.return_order_id
                LEFT JOIN service_card_order sco ON sco.order_id = rsco.order_id
                left join users on users.id= sco.user_id where rscr.pay_type=6 and users.type=2 and rsco.status=1 and sco.verify_status=0 and sco.shop_id=? and sco.user_id=?",array($sc_user->shop_id,$user_id));
            $arrears_shop_detail=$arrears_shop_detail-$service_return_amount[0]->amount;

            $result = array(
                'arrears_all' => $arrears_all_detail/100,
                'arrears_shop' => $arrears_shop_detail/100
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    public function remark_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'shop_id' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $shop_id = Input::get("shop_id");
            $user_id = Input::get("user_id");
//            $page_size = Input::get("page_size", 10);
//            $page = Input::get("page", 0);

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                $response = Lang::get("scs_error.user_token_not_exist_21006");
                break;
            }
            $user = Users::find($user_id);
            if(!$user){
                $response = Lang::get("scs_error.user_error_21009");
                break;
            }
            $count = ShopUserProperty::where('shop_id',$shop_id)->where('user_id',$user_id)->where
            ('user_type',$user->type)->count();
            $records = ShopUserProperty::where('shop_id',$shop_id)
                ->where('user_id',$user_id)
                ->where('user_type',$user->type)
//                ->skip($page_size*($page-1))
//                ->take($page_size)
                ->get();
            foreach($records as &$plan){
                $plan->liabler = '';
                $plan->shop_name = '';
                $plan->submitter = '';
                $shop = MaintenanceShops::find($plan->shop_id);
                if($shop){
                    $users = SCUser::where('shop_id',$plan->shop_id)->where('status',1)->where
                    ('title',1)->select('id','real_name')->get();
                    $sc_user = SCUser::find($plan->created_by);
                    foreach ($users as $us){
                        $plan->charge_man .= ($us->real_name . "/");
                    }
                    $plan->charge_man = substr($plan->charge_man,0,strlen($plan->charge_man) - 1);
                    $plan->liabler = $plan->charge_man;
                    unset($plan->charge_man);
                    $plan->shop_name = $shop->name;
                    $plan->remark = $plan->user_comments;
                    unset($plan->user_comments);
                    unset($plan->user_type);
                    $plan->submitter = $sc_user ? $sc_user->user_name : '';
                }

            }
            $result = array(
                'count' => $count,
                'records' => $records
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "remark_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    public function remark_store(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'shop_id' => 'required',
                'user_id' => 'required',
                'shop_name' => 'required',
                'remark' => 'required',
                'submitter' => 'required',
//                'liabler' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $shop_id = Input::get("shop_id");
            $user_id = Input::get("user_id");
            $shop_name = Input::get("shop_name");
            $remark = Input::get("remark");
            $submitter = Input::get("submitter");
            $liabler = Input::get("liabler")?Input::get("liabler"):'';

            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                $response = Lang::get("scs_error.user_token_not_exist_21006");
                break;
            }
            try {
                $user = Users::find($user_id);
                if(!$user){
                    $response = Lang::get("scs_error.user_error_21009");
                    break;
                }
                $record = new ShopUserProperty();
                $record->shop_id = $shop_id;
                $record->user_id = $user_id;
                $record->user_type = $user->type;
                $record->user_comments = $remark;
                $record->created_by = $sc_user->id;
                $record->created_at = Common::currentTimeString();
                $record->updated_at = Common::currentTimeString();
                $record->save();

                $result = array('id'=> $record->id );
                $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
            }catch(Exception $e){
                DB::rollback();
                $response = array('code' => -1, 'msg' => '保存失败');
                break;
            }
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "remark_store", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    public function detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get("user_id");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            Account::get_account_no($user_id);

            $count = UserAccount::where('user_id',$user_id)->count();
            $account = UserAccount::where('user_id',$user_id)->get()->toArray();
//            $detail = UserAccountDeatails::where('user_id',$user_id)
//                ->groupBy('acount_type')
//                ->get()
//                ->toArray();
            $detail = DB::select('select acount_type,sum(balance)/100 as balance ,sum(credit)/100 as credit from user_account_details where user_id = ? group by acount_type', array($user_id));
            foreach ($account as &$_account){
                $_account['balance'] = $_account['balance']/100;
                $_account['credit'] = $_account['credit']/100;
            }

//            foreach ($detail as &$_detail){
//                $_detail['balance'] = $_detail['balance']/100;
//                $_detail['credit'] = $_detail['credit']/100;
//            }


            $result = array(
                'count' => $count,
                'account' => $account,
                'detail' => $detail
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    public function journal(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }

            //传入参数
            $token = Input::get('token');
            $user_id = Input::get("user_id");
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 0);
            $start_date = Input::get("start_date");
            $stop_date = Input::get("stop_date");

            //传入参数
            $response = array('code' => 0, 'msg' => 'ok');
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }

            $account_nos = UserAccountDeatails::where('user_id',$user_id)->select('account_no')->get()->toArray();
            $journals = JournalAccount::OrderBy('journal_account.created_at','desc')
                ->whereIn('account_no',$account_nos)
                ->leftJoIn('subject_account','subject_account.code','=','journal_account.subject')
                ->select('journal_account.*','subject_account.name as subject_name')
                ->skip($page_size*($page-1))
                ->take($page_size);

            $count = JournalAccount::whereIn('account_no',$account_nos);


            if($start_date != '' && $stop_date != ''){
                $journals->whereBetween('journal_account.created_at',array($start_date,$stop_date));
                $count->whereBetween('journal_account.created_at',array($start_date,$stop_date));
            }

            $journals = $journals->get()->toArray();
            $count = $count->count();

            foreach ($journals as &$_journals){
                $_journals['amount'] = $_journals['amount']/100;
            }

            $result = array(
                'count' => $count,
                'journals' => $journals
            );
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $result);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "journals", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-05-17 17:32:16
     * @Description: 用于门店 前台帮助客户充值
     */
    public function user_recharge(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
                'amount' => 'required:max:1000000',
                'pay_type' => 'required',
                'source' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");      
            $user_id=Input::get("user_id");
            $amount=Input::get("amount")*100;
            $pay_type=Input::get("pay_type");
            $id_card=Input::get("id_card");
            $user_name=Input::get("user_name");
            $pass_word=Input::get("pass_word");
            $driver_id=Input::get("driver_id");
            $source=Input::get("source");
            if(!isset(AcountUserRecharge::$sc_paytype[$pay_type])||!in_array($source,AcountUserRecharge::$sc_paytype_source[$pay_type])){//验证支付方式
                $response = Lang::get("scs_error.order_pay_type_error_40096");
                break;
            }
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $user=Users::where("id",$user_id)->where("status",1)->first();
            if(is_null($user)){
                $response = Lang::get("scs_error.order_user_notexit_error_40097");
                break;
            }
            //检查身份证后四位
            if($user->type==1){//个人用户判断身份证
                if(is_null($id_card)||strlen($id_card)!=4){
                    $response = Lang::get("scs_error.order_user_id_card_error_40098");
                    break;
                }else{
                    if((substr($user->id_card,-4)!=$id_card)){
                        $response = Lang::get("scs_error.order_user_id_card_error_40098");
                        break;
                    }
                }            
            }else{//用户名密码判断 组织机构代码验证 有就算有
                $sc=SCUser::where('user_name',$user_name)->where('password',strtoupper(md5($pass_word)))->where('status',1)->first();
                if(is_null($sc)||$sc->shop_id!=$sc_user->shop_id){
                    $response = Lang::get("scs_error.scs_user_not_exiet21009");
                    break;
                }
                if($sc->title!=1){
                    $response = Lang::get("scs_error.login_user_error_21016");
                    break;
                }
                $c=Companys::find($user->id);
                if(is_null($c)||!$c->identification_number){
                    $response = Lang::get("scs_error.order_user_id_card_error_40099");
                    break;
                }
            }
            // if($pay_type!=20){
            //     $arrid=Account::service_recharge($user->id,$pay_type,1,$amount,'sc',$sc_user->id,$sc_user->shop_id);
            //     $response = array('code' => 0, 'msg' => 'ok', 'result' => array("arrid"=>$arrid));
            // }else{
            //     $account_no = Account::get_account_details_no($user->id,$sc_user->shop_id,1);
            //     $aur=new AcountUserRecharge();
            //     $aur->user_id=$user->id;
            //     $aur->account_no=$account_no;
            //     $aur->pay_type=$pay_type;
            //     $aur->current_amount=$amount;
            //     $aur->amount=$amount;
            //     $aur->status=5;
            //     $aur->create_type='sc';
            //     $aur->create_by=$sc_user->id;
            //     // $aur->tran_no=$tran_no;
            //     $aur->shop_id=$sc_user->shop_id;
            //     // $aur->implement_time=Common::currentTimeString();
            //     $aur->sources=2;
            //     $aur->save();

            //     $mpd=MaintenancePosDevice::where("id",$driver_id)->where('shop_id',$sc_user->shop_id)->where('status',1)->first();
            //     if(is_null($mpd)){
            //       DB::rollback();
            //       $response = Lang::get("scs_error.order_pay_driver_error_40116");
            //       return $response;
            //     }

            //     // OrderPay::where("id",$o_p->id)->update(array("status"=>5,"sources"=>2,"implement_time"=>null,"tran_no"=>''));
            //     //调用智能pos 支付
            //     $w=WposRecord::prepareOrder(1,$aur->id,$aur->id,$amount,$user->id,$sc_user->shop_id,$mpd->device_no,$sc_user->id);
            //     if($w){
            //       AcountUserRecharge::where("id",$aur->id)->update(array("status"=>5));
            //     }else{
            //       AcountUserRecharge::where("id",$aur->id)->update(array("status"=>2));
            //     }
            //     $response = array('code' => 0, 'msg' => 'ok', 'result' => array("arrid"=>$aur->id,"pay_type"=>$pay_type));
            // }      

            if($source==1){                     //说明是系统充值 暂时pay_type 一定是"1"=>"线下支付现金","7"=>"线下支付刷卡", '11'=>'线下支票',
                $arrid=Account::service_recharge($user->id,$pay_type,1,$amount,'sc',$sc_user->id,$sc_user->shop_id);
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("arrid"=>$arrid));
            }else{                              //说明是 走pos支付 暂时pay_type 一定是"1"=>"线下支付现金","7"=>"线下支付刷卡", '20'=>'posB扫C',
                $account_no = Account::get_account_details_no($user->id,$sc_user->shop_id,1);
                $aur=new AcountUserRecharge();
                $aur->user_id=$user->id;
                $aur->account_no=$account_no;
                $aur->pay_type=$pay_type;
                $aur->current_amount=$amount;
                $aur->amount=$amount;
                $aur->status=5;
                $aur->create_type='sc';
                $aur->create_by=$sc_user->id;
                // $aur->tran_no=$tran_no;
                $aur->shop_id=$sc_user->shop_id;
                // $aur->implement_time=Common::currentTimeString();
                $aur->sources=2;
                $aur->save();

                $mpd=MaintenancePosDevice::where("id",$driver_id)->where('shop_id',$sc_user->shop_id)->where('status',1)->first();
                if(is_null($mpd)){
                  DB::rollback();
                  $response = Lang::get("scs_error.order_pay_driver_error_40116");
                  return $response;
                }
                //如果 是20就是指定b扫C  扫一扫设定为1 指定支付方式为空
                $call_scan=($pay_type==20?1:0); 
                $pay_type=($pay_type==20?0:$pay_type);
                // OrderPay::where("id",$o_p->id)->update(array("status"=>5,"sources"=>2,"implement_time"=>null,"tran_no"=>''));
                //调用智能pos 支付
                $w=WposRecord::prepareOrder(1,$aur->id,$aur->id,$amount,$user->id,$sc_user->shop_id,$mpd->device_no,$sc_user->id,$pay_type,$call_scan);
                if($w){
                  AcountUserRecharge::where("id",$aur->id)->update(array("status"=>5));
                }else{
                  AcountUserRecharge::where("id",$aur->id)->update(array("status"=>2));
                }
                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("arrid"=>$aur->id,"pay_type"=>$pay_type));
            }        
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "journals", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-05-18 10:35:43
     * @Description: 用户可以撤销的充值记录
     */
    public function can_cancel(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
                'acount_type' => 'required|in:1,2',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");      
            $user_id=Input::get("user_id");
            $acount_type=Input::get("acount_type");
            
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $user=Users::where("id",$user_id)->where("status",1)->first();
            if(is_null($user)){
                $response = Lang::get("scs_error.order_user_notexit_error_40097");
                break;
            }
            if($user->type==2){//企业用户不能撤销
                $response = Lang::get("scs_error.user_not_car_cancel_error_40100");
                break;           
            }   
            $account_no = Account::get_account_details_no($user_id,$sc_user->shop_id,$acount_type);
            $finally=array();
            $aur=AcountUserRecharge::where("account_no",$account_no)->where("pay_type","!=","14")->where("status",1)->where("implement_time",">",date("Y-m-d H:i:s",time()-24*60*60))->orderBy("implement_time","desc")->get();
            foreach ($aur as $_aur) {
                //看看有没有充值记录调整
                $aar=AcountAdjustmentRecord::where("aurr_id",$_aur->id)->first();
                if($aar){
                    continue;
                }
                //检查又没用使用过 该条记录
                //没有被消费过 两个金额相同                

                $t_aurs=AcountUserRechargeSpend::where("aurr_id",$_aur->id)->first();
                if(is_null($t_aurs)&&$_aur->current_amount==$_aur->amount){
                    $_aur->implement_time_two=date("Y-m-d H:i:s",strtotime($_aur->implement_time)+Config::get("config.report_time_diff"));
                    $_aur->current_amount=bcdiv($_aur->current_amount,100,2);
                    $_aur->amount=bcdiv(($_aur->amount),100,2);
                    $finally[]=$_aur;
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("aur_info"=>$finally));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "can_cancel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-05-18 11:31:25
     * @Description: 撤销用户充值记录
     */
    public function cancel_aur(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'aur_id' => 'required',
                'user_name' => 'required',
                'pass_word' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");      
            $aur_id=Input::get("aur_id");
            $desc=Input::get("desc");
            $user_name=Input::get("user_name");
            $pass_word=Input::get("pass_word");
            
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $sc=SCUser::where('user_name',$user_name)->where('password',strtoupper(md5($pass_word)))->where('status',1)->first();
            if(is_null($sc)||$sc->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.scs_user_not_exiet21009");
                break;
            }
            if($sc->title!=1){
                $response = Lang::get("scs_error.login_user_error_21016");
                break;
            }
            $aur=AcountUserRecharge::find($aur_id);
            if(is_null($aur)||$aur->status!=1){
                $response = Lang::get("scs_error.aur_record_notexit_error_40101");
                break;
            }
            //关闭 两种类型的撤销
            if(in_array($aur->pay_type, array(2,3))&&$aur->sources==2){
                $response = Lang::get("scs_error.aur_undo_type_error_40126");
                break;
            }

            if(strtotime($aur->implement_time)+24*60*60<time()){
                $response = Lang::get("scs_error.order_time_error_40115");
                break;
            }

            $t_aurs=AcountUserRechargeSpend::where("aurr_id",$aur->id)->first();
            if(!is_null($t_aurs)||$aur->current_amount!=$aur->amount){
                $response = Lang::get("scs_error.aur_record_user_error_40102");
                break;
            }
            if($aur->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.aur_record_shop_error_40103");
                break;
            }
            $user=Users::where("id",$aur->user_id)->where("status",1)->first();
            if(is_null($user)){
                $response = Lang::get("scs_error.order_user_notexit_error_40097");
                break;
            }
            if($user->type==2){//企业用户不能撤销
                $response = Lang::get("scs_error.user_not_car_cancel_error_40100");
                break;           
            }
            $response=AcountUserUndo::cancel_aur($aur->user_id,$aur->id,'sc',$sc_user->id,$sc->id,$desc);
            // $response = array('code' => 0, 'msg' => 'ok', 'result' => array("auu_id"=>$auu_id));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "can_cancel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-05-18 13:29:24
     * @Description: 用户退款接口
     */
    public function return_amount(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
                'amount' => 'required',
                'pay_type' => 'required',
                'user_name' => 'required',
                'pass_word' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");      
            $user_id=Input::get("user_id");
            $amount=Input::get("amount")*100;
            $pay_type=Input::get("pay_type");
            $desc=Input::get("desc");
            $user_name=Input::get("user_name");
            $pass_word=Input::get("pass_word");
            
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $sc=SCUser::where('user_name',$user_name)->where('password',strtoupper(md5($pass_word)))->where('status',1)->first();
            if(is_null($sc)||$sc->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.scs_user_not_exiet21009");
                break;
            }
            if($sc->title!=1){
                $response = Lang::get("scs_error.login_user_error_21016");
                break;
            }
            if(!isset(AcountUseRefund::$return_pay_type[$pay_type])){//验证支付方式
                $response = Lang::get("scs_error.amount_cant_return_paytype_error_40106");
                break;
            }
            $user=Users::where("id",$user_id)->where("status",1)->first();
            if(is_null($user)){
                $response = Lang::get("scs_error.order_user_notexit_error_40097");
                break;
            }
            $uad_balance=UserAccountDeatails::where("user_id",$user->id)->where("acount_type",1)->sum("balance");
            if($uad_balance<$amount){//说明账户不存在或者不足以支付
                $response = Lang::get("scs_error.amount_cant_return_error_40105");
                break;
            }
            $response=AcountUseRefund::return_amount($user_id,$pay_type,$sc_user->shop_id,$amount,"sc",$sc_user->id,$sc->id,$desc);
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "can_cancel", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }



   /**
    * @Author:      lyt
    * @DateTime:  2017-05-18 15:15:53
    * @Description: 期初余额列表
    */
    public function begin_balance_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");      
            $car_no=Input::get("car_no");
            $page_size = Input::get("page_size", 25);
            $page = Input::get("page", 1);
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $bb=BeginBalance::where("shop_id",$sc_user->shop_id)->orderBy("created_at","desc");
            $db_sql="SELECT sum(bb.amount) amount FROM `begin_balance` bb LEFT JOIN (  SELECT * FROM  begin_blance_recharge   WHERE       `status` = 1) bbr ON bbr.bg_id = bb.id  where bb.shop_id=? and  bbr.id is null";
            if($car_no){
                $bb=$bb->where("car_no","like","%".$car_no."%");
                $db_sql=$db_sql." and bb.car_no like '%".$car_no."%'";
            }
            $amount=DB::select($db_sql,array($sc_user->shop_id));
            $count = $bb->count();
            $bb=$bb->skip($page_size*($page-1))
                ->take($page_size)
                ->get();
            foreach ($bb as $_bb) {
                $bbr=BeginBalanceRecharge::where('begin_blance_recharge.bg_id',$_bb->id)->where("status",1)->first();
                $_bb->canuser_amount=isset($bbr)?0:bcdiv($_bb->amount,100,2);
                $_bb->current_amount=bcdiv($_bb->current_amount,100,2);
                $_bb->amount=bcdiv(($_bb->amount),100,2);               
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"amount_all"=>bcdiv($amount[0]->amount,100,2),"bb_info"=>$bb));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "begin_balance_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

   /**
    * @Author:      lyt
    * @DateTime:  2017-05-18 15:57:54
    * @Description: 起初余额详情
    */
    public function begin_balance_detail(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'bb_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");      
            $bb_id=Input::get("bb_id");
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $bb=BeginBalance::where("id",$bb_id)->where("shop_id",$sc_user->shop_id)->first();
            if(is_null($bb)){
                $response = Lang::get("scs_error.b_blance_notexit_error_40107");
                break;
            }
            
            $bbr=BeginBalanceRecharge::leftjoin('users','begin_blance_recharge.user_id','=','users.id')
                ->leftjoin('acount_user_recharge_record','acount_user_recharge_record.id','=','begin_blance_recharge.aurr_id')
                ->leftjoin('sc_user','sc_user.id','=','begin_blance_recharge.created_by')
                ->leftjoin('maintenance_shops','maintenance_shops.id','=','acount_user_recharge_record.shop_id')
                ->where('begin_blance_recharge.bg_id',$bb->id)->select(array("begin_blance_recharge.*","users.phone","users.real_name","users.sex","acount_user_recharge_record.tran_no","sc_user.real_name as sc_user_name","maintenance_shops.name as shop_name"))->get();
            $status_bbr=null;
            foreach ($bbr as $_bbr) {
                if($_bbr->status==1){
                    $status_bbr=$_bbr;
                }
                $_bbr->amount=bcdiv($_bbr->amount,100,2);
            }
            $bb->canuser_amount=isset($status_bbr)?0:bcdiv($bb->amount,100,2);
            $bb->amount=bcdiv($bb->amount,100,2);
            $bb->current_amount=bcdiv($bb->current_amount,100,2);
            // if($bbr){
            //     $bbr->amount=bcdiv($bbr->amount,100,2);
            // }         
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("bb_info"=>$bb,"bbr_info"=>$bbr));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "begin_balance_detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-05-18 17:02:58
     * @Description: 期初划拨
     */
    public function begin_balance_recharge(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'bb_id' => 'required',
                "user_id"=>'required',
                "id_card"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");      
            $bb_id=Input::get("bb_id");
            $user_id=Input::get("user_id");
            $id_card=Input::get("id_card");
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $bb=BeginBalance::where("id",$bb_id)->where("shop_id",$sc_user->shop_id)->first();
            if(is_null($bb)){
                $response = Lang::get("scs_error.b_blance_notexit_error_40107");
                break;
            }
            $acount_type=$bb->type==1?2:1;//如果 该纪录是保险类型 账户类型为2 虚拟 如果不是 则为1 现金账户
            if(!isset(BeginBalanceRecharge::$acount_type[$acount_type])){//验证账户类型
                $response = Lang::get("scs_error.begin_balance_recharge_type_40110");
                break;
            }
            $user=Users::where("id",$user_id)->where("status",1)->first();
            if(is_null($user)){
                $response = Lang::get("scs_error.order_user_notexit_error_40097");
                break;
            }
            if($user->type==1){//个人用户判断身份证
                if(is_null($id_card)||strlen($id_card)!=4){
                    $response = Lang::get("scs_error.order_user_id_card_error_40098");
                    break;
                }else{
                    if((substr($user->id_card,-4)!=$id_card)){
                        $response = Lang::get("scs_error.order_user_id_card_error_40098");
                        break;
                    }
                }            
            }else{//企业用户不能划拨       
                $response = Lang::get("scs_error.begin_balance_recharge_40108");
                break;                
            }            
            $response = BeginBalance::rechange($bb_id,$user_id,$acount_type,$sc_user,$id_card);       
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "begin_balance_detail", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    //充值记录
    public function rechargeRecords(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "user_id"=>'required',
                "shop_id"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            $user_id = Input::get('user_id');
            $shop_id = Input::get('shop_id');
            $page_size = Input::get("page_size", 25);
            $page = Input::get("page", 1);
            $paytype = Orders::$paytype;
            $user=Users::find($user_id);
            $pay_status = OrderPayRecord::$pay_status;
            $pay_sources = AcountUserRecharge::$pay_sources;
            $select_records = AcountUserRecharge::where('user_id', $user_id)->where('pay_type','!=',14)->where('amount','>',0)->where('shop_id', $shop_id);
            $count = $select_records->count();
            $select_records = $select_records->orderBy('created_at', 'desc')
                ->skip($page_size * ($page - 1))
                ->take($page_size)
                ->select('id','created_at','updated_at','status','pay_type','implement_time','pay_id','amount','shop_id','user_id','tran_no','sources')
                ->get();
            foreach ($select_records as &$sr) {
                if ($sr->status === 3 || $sr->status === 4|| $sr->status === 2) {
                    $sr->status = 3;
                } elseif ($sr->status === 5) {
                    $sr->status = 2;
                } elseif ($sr->status === 6) {
                    $sr->status = 4;
                }
                $sr->status_name = $pay_status[$sr->status];
                $sr->pay_type_name = $paytype[$sr->pay_type];
                $sr->sources_name = $pay_sources[$sr->sources];
                $sr->amount = $sr->amount / 100;
                $sr->user_name = $user->real_name;
                $sr->user_phone = $user->phone;
            }
            $response['result']['count'] = $count;
            $response['result']['records'] = $select_records;
        }while(false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "rechargeRecords", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-06-21 18:42:23
     * @Description: 该门店未处理的充值记录撤销
     */
    public function can_stop_undo(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");
            $page_size = Input::get("page_size", 25);
            $page = Input::get("page", 1);
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $auu=AcountUserUndo::leftJoin("acount_user_recharge_record","acount_user_recharge_record.id","=","acount_user_undo_record.aurr_id")
            ->leftJoin("users","users.id","=","acount_user_undo_record.user_id")
            ->leftJoin("sc_user","sc_user.id","=","acount_user_undo_record.create_by")
            ->where("acount_user_undo_record.status",5)->where("acount_user_undo_record.shop_id",$sc_user->shop_id);
            if(Input::get("phone")){
                $auu=$auu->where("users.phone",Input::get("phone"));
            }
            if(Input::get("amount")){
                $auu=$auu->where("acount_user_recharge_record.amount",Input::get("amount")*100);
            }
            if(Input::get("start_time")){
                $auu=$auu->where("acount_user_undo_record.created_at",">",Input::get("start_time"));
            }
            if(Input::get("end_time")){
                $auu=$auu->where("acount_user_undo_record.created_at","<",Input::get("end_time"));
            }
            $count = $auu->count();
            $auu=$auu->skip($page_size * ($page - 1))->take($page_size)->select('acount_user_undo_record.id','users.id as user_id','users.real_name','users.phone','sc_user.id as sc_user_id','sc_user.real_name as sc_name','acount_user_recharge_record.id as re_id','acount_user_undo_record.created_at','acount_user_recharge_record.pay_type','acount_user_recharge_record.implement_time','acount_user_recharge_record.current_amount','acount_user_recharge_record.amount')->get();
            foreach ($auu as $_auu) {
                $_auu->current_amount=round($_auu->current_amount/100,2);
                $_auu->amount=round($_auu->amount/100,2);
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('count'=>$count,"aur_info"=>$auu));
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "can_stop_undo", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-06-22 10:28:53
     * @Description: 取消撤销中的撤销记录
     */
    public function cancen_undo(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");
            $id=Input::get("id");
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            $au=AcountUserUndo::find($id);
            if(is_null($au)||$au->status!=5||$au->shop_id!=$sc_user->shop_id){
                $response = Lang::get("scs_error.user_not_car_cancel_error_40118");
                break;
            }
            $aur=AcountUserRecharge::find($au->aurr_id);
            if($aur->sources==2){//说明支付途径是 pos 撤销 修改只修改充值记录的的 可用余额
                $wr=WposRecord::where("type",1)->where("buss_id",$aur->id)->first();
                $p_r=Pos::statusOrder($wr->id);
                if($p_r->status==0){
                    if($p_r->data->trade_status=="PAY"){
                        $aur->current_amount=$aur->amount;
                        $aur->status=1;
                        $aur->save();
                        $au->status=4;
                        $au->save();
                        $response = array('code' => 0, 'msg' => 'ok', 'result' => array("au_id"=>$au->id));
                        break;
                    }
                }              
            }            
            $response = Lang::get("scs_error.user_not_car_cancel_error_40123");
        } while (false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "cancen_undo", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    /**
     * @Author:      zy
     * @DateTime:  2017-07-18 10:28:53
     * @Description: 个人/企业退款记录
     */
    public function refundRecords(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'user_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            
            $shop_id = $sc_user->shop_id;
            $user_id = Input::get('user_id');
            $page = Input::get("page", 1);
            $page_num = Input::get("page_num",25);
            $user=Users::find($user_id);
            $start = ($page-1)*$page_num;//当前页显示的初始偏移量    
            
            $sql_1 = "select id,tran_no,shop_id,created_at,updated_at,pay_type,status,amount,null as pay_id,'tuikuan' as refund_type 
                    from acount_user_refund_record where user_id=? and shop_id = ?";
            $sql_2 = "select id,tran_no,shop_id,created_at,updated_at,pay_type,status,amount,pay_id,'chexiao' as refund_type 
                    from acount_user_undo_record where user_id=? and shop_id = ?";
            $sql = "select * from ({$sql_1} union all {$sql_2}) as b order by b.created_at desc limit {$start},{$page_num}";

            $refundRecords_info = DB::select($sql,array($user_id,$shop_id,$user_id,$shop_id));
            $sql_count = "select count(1) as count_num from ({$sql_1} union all {$sql_2}) a";
            $count_select = DB::select($sql_count,array($user_id,$shop_id,$user_id,$shop_id));

            if(!empty($refundRecords_info)){
               foreach($refundRecords_info as $k=>$v){
                   $v->amount = round(bcdiv($v->amount,100,6),2);
               } 
            }
            $response['result']['count'] = $count_select[0]->count_num;
            $response['result']['info'] = $refundRecords_info;
        }while(false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "refundRecords", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      zy
     * @DateTime:  2017-07-18 10:28:53
     * @Description: 个人/企业退款冲减明细
     */
    public function refundRecordsList(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'refund_type' => 'required',
                'refund_id'=>'required',
                'user_id'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.login_token_error_21005");
                break;
            }
            //传入参数      
            $token=Input::get("token");
            //传入参数
            $sc_user=$this->verificationSCSUserToken($token,$response);
            if(is_null($sc_user)){
                break;
            }
            
            $refund_type = Input::get('refund_type');
            $user_id = Input::get('user_id');
            $refund_id = Input::get('refund_id');
            if ($refund_type == "tuikuan") {
                $sql = "select a.id,a.aurr_id,a.amount,b.tran_no from acount_user_recharge_spend_record as a 
                        left join acount_user_refund_record as b on b.id=a.buss_id 
                        where a.type=4 and b.id=?";
            }else {
                $sql = "select id,aurr_id,amount,tran_no from acount_user_undo_record where id = ?";
            }

            $recharge = DB::select($sql,array($refund_id));
            
            if (!empty($recharge)) {
                foreach($recharge as $k=>$value){
                    $recharge[$k]->amount = round(bcdiv($recharge[$k]->amount,100,6),2);
                    $array = AcountUserRecharge::RechargeInfo($value->aurr_id); //根据充值记录，查找对应的门店名称和账户标虚
                    $key = $array['shop_id'].'_'.$array['acount_type'];
                    if(isset($return_money[$key])){
                        $return_money[$key]['amount'] += $recharge[$k]->amount;
                    } else {
                        $return_money[$key] = $array;
                        $return_money[$key]['amount'] = $recharge[$k]->amount;
                    }
                }
            }

            $response['result']['recharge'] = $recharge;
            $response['result']['return_money'] = array_values($return_money);
        }while(false);
        Log::info("info", array("system" => "scs" ,"model" => "account", "event" => "refundRecordsList", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
}


